//
//  QDTimeVerifier.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/27.
//  Copyright © 2019 YueWen. All rights reserved.
//

import Foundation

/// 时间验证者
protocol QDTimeVerifier {
    
    /// 限制时间，默认60s
    var limitTime: Int { get }
    /// 时间
    func time(key: String) -> Int
    /// 检测时间是否已经过时
    @discardableResult func checkTimeIsOut(key: String) -> Bool
    
    /// 存储当前时间操作
    func saveCurrentTime(key: String)
}



extension QDTimeVerifier {
    
    var limitTime: Int {
        return 60
    }
    
    func time(key: String) -> Int {
        
        let timer = UserDefaults.standard.integer(forKey:key)
        UserDefaults.standard.synchronize()
        
        return timer
    }
    
    
    /// 存储验证码操作
    func saveCurrentTime(key: String){
        
        //获取当前时间戳
        let codeBtnClickTime = Int(NSDate().timeIntervalSince1970)
        //存到本地
        UserDefaults.standard.set(codeBtnClickTime, forKey: key)
        UserDefaults.standard.synchronize()
    }
    
    
    /// 进行检测
    @discardableResult func checkTimeIsOut(key: String) -> Bool {
        
        let timer = UserDefaults.standard.integer(forKey:key)
        UserDefaults.standard.synchronize()
        
        if timer == 0 { return true }
        let currentTime = Int(Date().timeIntervalSince1970)
        
        print("distance = \(currentTime - timer)")
        if currentTime - timer >= limitTime { return true }
        return false
    }
    
}
